package com.yupi.apiback.config;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.yupi.apiback.model.entity.SuperModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

/**
 * MyBatis-Plus自动填充配置类
 *
 * @author 杨海峰
 * @date 2023-05-26 22:51
 */
@Slf4j
@Configuration
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Object originalObject = metaObject.getOriginalObject();
        SuperModel superModel = BeanUtil.toBean(originalObject, SuperModel.class);
        String createBy = superModel.getCreateBy();
        String updateBy = superModel.getUpdateBy();
        // 如果创建人数据为空，则进行自动填充
        if (StrUtil.hasBlank(createBy, updateBy)) {
            // 获取当前登录用户信息
            this.strictInsertFill(metaObject, "createBy", String.class, "admin");
            this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class);
            this.strictInsertFill(metaObject, "updateBy", String.class, "999");
            this.strictInsertFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "updateBy", String.class, "999");
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
    }
}
